package com.yihang.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yihang.usercenter.common.BaseResponse;
import com.yihang.usercenter.common.ErrorCode;
import com.yihang.usercenter.common.ResultUtils;
import com.yihang.usercenter.exception.BusinessException;
import com.yihang.usercenter.model.User;
import com.yihang.usercenter.model.request.UserLoginRequest;
import com.yihang.usercenter.model.request.UserRegisterRequest;
import com.yihang.usercenter.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.yihang.usercenter.contsant.UserConstant.ADMIN_ROLE;
import static com.yihang.usercenter.contsant.UserConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 注册
     * @param userRegisterRequest 注册
     * @return 注册
     */
    @PostMapping("/register")
    public BaseResponse userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        // 判断是否为空
       if (userRegisterRequest == null){
           throw new BusinessException(ErrorCode.PARAMS_ERROR);
       }
       // 校验请求参数是否符合，不参与业务逻辑
       String username = userRegisterRequest.getUsername();
       String userAccount = userRegisterRequest.getUserAccount();
       String userPassword = userRegisterRequest.getUserPassword();
       String checkPassword = userRegisterRequest.getCheckPassword();
       String planetCode = userRegisterRequest.getPlanetCode();
       // 有一个不符合
       if (StringUtils.isAnyBlank(username,userAccount, userPassword, checkPassword, planetCode)){
           return null;
       }
       long result = userService.userRegister(username,userAccount, userPassword, checkPassword,planetCode);
        return ResultUtils.success(result);
    }


    /**
     * 登录
     * @param userLoginRequest 登录
     * @param request 登录请求参数
     * @return 登录
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        // 判断是否为空
        if (userLoginRequest == null){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        // 校验请求参数是否符合，不参与业务逻辑
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        // 有一个不符合
        if (StringUtils.isAnyBlank(userAccount, userPassword)){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount,userPassword,request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request){
        // 判断是否为空
        if (request == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /** 获取用户的登录信息
     *
     * @param request 请求用户信息
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request){
        // 仅管理员查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        // 类型转换 这个要注意强转 注意判断
        User currentUser = (User) userObj;
        if (currentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        // 从数据库重新查一遍用户信息
        long userId = currentUser.getId();
        // todo: 校验用户是否合法
        User user = userService.getById(userId);
        User SafetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(SafetyUser);

    }

    /**
     * 查询
     * @param username 查询用户
     * @return
     */
    @GetMapping("/search")
    private BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request){
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 是否有userAccount
        if (StringUtils.isNotBlank(username)){
            // 模糊查询
            queryWrapper.like("username",username);
        }
        List<User> userList = userService.list(queryWrapper);
        // 把userList遍历成stream数据流，遍历sureList中的每一个元素，
        // 将UserPassword设置为空，最后拼接一个完整的list
        List<User> list = userList.stream()
                .map(user -> userService.getSafetyUser(user))
                .collect(Collectors.toList());
        return ResultUtils.success(list);

    }

    /**
     * 删除
     * @param id 删除id
     * @return
     */
    @PostMapping("/delete")
    private BaseResponse<Boolean> deleteUsers(@RequestBody long id, HttpServletRequest request){
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 删除removeById 逻辑删除 mybatis-plus框架进行转化
        boolean b =  userService.removeById(id);
        return ResultUtils.success(b);


    }

    /**
     * 是否为管理员
     * @param request 管理员
     * @return
     */
    private boolean isAdmin(HttpServletRequest request) {
        // 仅管理员查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        // 类型转换 这个要注意强转 注意判断
        User user = (User) userObj;
        return user == null || user.getUserRole() == ADMIN_ROLE;

    }



}




